﻿using System;
using System.Web.UI;
using Project.BIZ;
using Project.DTO;
using Project.IBIZ;

namespace Project.UI
{
    public partial class OrderProduct : Page
    {
        private readonly IFindUnitPriceBIZ _findUnitPrice = new FindUnitPriceBIZ();

        /// <summary>
        ///     Global instance from TransactionOrderProduct in Business layer
        /// </summary>
        private readonly ITransactionOrderProductBIZ _transactionOrderProduct = new TransactionOrderProductBIZ();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Constants.SessionUserName] != null)
            {
                var curUser = (string) Session[Constants.SessionUserName];
                int proId = LoadProductId();
                var price = _findUnitPrice.FindUnitPrice(proId).Unit_Price;
                if (price != null)
                {
                    decimal unitPrice = price.Value;
                    var productOrder = new ProductOrder
                    {
                        UserName = curUser,
                        TotalPrice = unitPrice*1,
                        ProductId = proId,
                        Quantity = 1,
                        UnitPrice = unitPrice
                    };

                    _transactionOrderProduct.OrderProduct(productOrder);
                }
                Response.Redirect(Constants.DefaultPage);
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "loginRequire", "<script>alert('You must login to continute!');</script>");
                Response.Redirect(Constants.LoginPage);
            }
        }

        private int LoadProductId()
        {
            int productId = -1;
            int.TryParse(Request.QueryString[Constants.OrderIdFromAddressBar], out productId);
            return productId;
        }
    }
}